<template>
  <div class="attendance-container">
    <div class="header">
      <h2>员工出勤统计</h2>
      <div class="filter-group">
        <el-radio-group v-model="timeType" @change="handleTimeTypeChange">
          <el-radio label="day">当日</el-radio>
          <el-radio label="month">当月</el-radio>
          <el-radio label="year">当年</el-radio>
          <el-radio label="custom">自定义</el-radio>
        </el-radio-group>

        <el-date-picker
            v-if="timeType === 'custom'"
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
        />
      </div>
    </div>

    <div class="stats-card-group">
      <el-card class="stat-card">
        <div class="stat-info">
          <p class="stat-label">总出勤率</p>
          <p class="stat-value">{{ attendanceRate.toFixed(2) }}%</p>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-info">
          <p class="stat-label">全勤人数</p>
          <p class="stat-value">{{ fullAttendanceCount }}</p>
          <p class="stat-desc">人</p>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-info">
          <p class="stat-label">迟到人数</p>
          <p class="stat-value">{{ lateCount }}</p>
          <p class="stat-desc">人</p>
        </div>
      </el-card>
    </div>

    <div class="charts-row">
      <el-card class="chart-card">
        <div class="chart-container">
          <h3>员工出勤详情</h3>
          <div ref="detailChartRef" class="chart"></div>
        </div>
      </el-card>

      <el-card class="chart-card">
        <div class="chart-container">
          <h3>每日出勤情况</h3>
          <div ref="dailyChartRef" class="chart"></div>
        </div>
      </el-card>
    </div>

<!--    <el-card class="chart-card">-->
<!--      <div class="chart-container">-->
<!--        <h3>全勤员工</h3>-->
<!--        <el-table :data="fullAttendanceEmployees" border style="width: 100%;">-->
<!--          <el-table-column prop="id" label="员工ID" width="100"></el-table-column>-->
<!--          <el-table-column prop="name" label="员工姓名" width="150"></el-table-column>-->
<!--          <el-table-column prop="attendanceDays" label="出勤天数"></el-table-column>-->
<!--          <el-table-column prop="attendanceRate" label="出勤率" formatter="formatPercentage"></el-table-column>-->
<!--        </el-table>-->
<!--      </div>-->
<!--    </el-card>-->
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElRadioGroup, ElRadio, ElDatePicker, ElCard, ElTable, ElTableColumn } from 'element-plus';
import * as echarts from 'echarts';
import http from '@/axios/http';

/* ---------- 类型 ---------- */
interface Attendance {
  id: number;
  employeeId: number;
  attendanceDate: string; // yyyy-MM-dd
  isSigned: 0 | 1;
  isLate: 0 | 1;
  employeeName?: string;
}

/* ---------- 响应式 ---------- */
const timeType = ref<'day' | 'month' | 'year' | 'custom'>('month');
const dateRange = ref<string[]>([]);
const filteredAttendance = ref<Attendance[]>([]);

const attendanceRate = ref(0);
const fullAttendanceCount = ref(0);
const lateCount = ref(0);
const fullAttendanceEmployees = ref<any[]>([]);

/* 图表 DOM */
const detailChartRef = ref<HTMLDivElement | null>(null);
const dailyChartRef = ref<HTMLDivElement | null>(null);
let detailChart: echarts.ECharts | null = null;
let dailyChart: echarts.ECharts | null = null;

let allAttendance: Attendance[] = [];

/* ---------- 拿数据 ---------- */
const fetchAttendance = async () => {
  const { data } = await http.post('/glsb/get_all_attendance', { pageNum: 1, pageSize: 9999 });
  allAttendance = data.data?.records || [];
  filterAttendance();
};

/* ---------- 过滤 ---------- */
const filterAttendance = () => {
  const today = new Date();
  let list = [...allAttendance];

  switch (timeType.value) {
    case 'day': {
      const d = today.toISOString().slice(0, 10);
      list = list.filter(r => r.attendanceDate === d);
      break;
    }
    case 'month': {
      const m = today.toISOString().slice(0, 7);
      list = list.filter(r => r.attendanceDate.startsWith(m));
      break;
    }
    case 'year': {
      const y = today.getFullYear().toString();
      list = list.filter(r => r.attendanceDate.startsWith(y));
      break;
    }
    case 'custom': {
      if (dateRange.value.length === 2) {
        const [s, e] = dateRange.value;
        list = list.filter(r => r.attendanceDate >= s && r.attendanceDate <= e);
      }
      break;
    }
  }
  filteredAttendance.value = list;
  updateStats();
  renderCharts();
};

/* ---------- 统计 ---------- */
const updateStats = () => {
  const total = filteredAttendance.value.length;
  const attended = filteredAttendance.value.filter(r => r.isSigned === 1).length;
  attendanceRate.value = total ? (attended / total) * 100 : 0;

  const lateIds = new Set(filteredAttendance.value.filter(r => r.isLate === 1).map(r => r.employeeId));
  lateCount.value = lateIds.size;

  /* 全勤员工：出勤天数=总天数 且 无迟到 */
  const empMap: Record<number, { id: number; name: string; total: number; attended: number; late: number }> = {};
  filteredAttendance.value.forEach(r => {
    const id = r.employeeId;
    const name = r.employeeName || `员工${id}`;
    if (!empMap[id]) empMap[id] = { id, name, total: 0, attended: 0, late: 0 };
    empMap[id].total++;
    if (r.isSigned === 1) empMap[id].attended++;
    if (r.isLate === 1) empMap[id].late++;
  });
  fullAttendanceEmployees.value = Object.values(empMap)
      .filter(e => e.total > 0 && e.attended === e.total && e.late === 0)
      .map(e => ({ ...e, attendanceRate: 100 }));
  fullAttendanceCount.value = fullAttendanceEmployees.value.length;
};

/* ---------- 绘图 ---------- */
const renderCharts = () => {
  if (!detailChartRef.value || !dailyChartRef.value) return;
  detailChart && detailChart.dispose();
  dailyChart && dailyChart.dispose();

  detailChart = echarts.init(detailChartRef.value);
  dailyChart = echarts.init(dailyChartRef.value);

  /* 1. 员工堆叠柱状图 */
  const empMap: Record<string, { attended: number; late: number; absent: number }> = {};
  filteredAttendance.value.forEach(r => {
    const name = r.employeeName || `员工${r.employeeId}`;
    if (!empMap[name]) empMap[name] = { attended: 0, late: 0, absent: 0 };
    if (r.isSigned === 1) {
      empMap[name].attended++;
      if (r.isLate === 1) empMap[name].late++;
    } else {
      empMap[name].absent++;
    }
  });
  const names = Object.keys(empMap);
  detailChart.setOption({
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    legend: { data: ['出勤', '迟到', '缺勤'] },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'value', axisLabel: { formatter: '{value} 天' } },
    yAxis: { type: 'category', data: names },
    series: [
      { name: '出勤', type: 'bar', stack: 'total', data: names.map(n => empMap[n].attended), itemStyle: { color: '#67c23a' } },
      { name: '迟到', type: 'bar', stack: 'total', data: names.map(n => empMap[n].late), itemStyle: { color: '#e6a23c' } },
      { name: '缺勤', type: 'bar', stack: 'total', data: names.map(n => empMap[n].absent), itemStyle: { color: '#f56c6c' } }
    ]
  });

  /* 2. 每日出勤率折线 */
  const dateMap: Record<string, { total: number; attended: number; late: number }> = {};
  filteredAttendance.value.forEach(r => {
    const d = r.attendanceDate;
    if (!dateMap[d]) dateMap[d] = { total: 0, attended: 0, late: 0 };
    dateMap[d].total++;
    if (r.isSigned === 1) dateMap[d].attended++;
    if (r.isLate === 1) dateMap[d].late++;
  });
  const dates = Object.keys(dateMap).sort();
  const attRates = dates.map(d => (dateMap[d].attended / dateMap[d].total) * 100);
  const lateRates = dates.map(d => (dateMap[d].late / dateMap[d].total) * 100);
  dailyChart.setOption({
    tooltip: { trigger: 'axis' },
    legend: { data: ['出勤率', '迟到率'] },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'category', boundaryGap: false, data: dates },
    yAxis: { type: 'value', axisLabel: { formatter: '{value}%' }, max: 100 },
    series: [
      { name: '出勤率', type: 'line', data: attRates, smooth: true, itemStyle: { color: '#67c23a' } },
      { name: '迟到率', type: 'line', data: lateRates, smooth: true, itemStyle: { color: '#e6a23c' } }
    ]
  });
};

/* ---------- 事件 ---------- */
const handleTimeTypeChange = () => filterAttendance();
const handleDateRangeChange = () => filterAttendance();

/* ---------- 挂载 ---------- */
onMounted(() => {
  fetchAttendance();
});
</script>
<style scoped>
.attendance-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-group {
  display: flex;
  gap: 15px;
  align-items: center;
}

.stats-card-group {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.stat-card {
  flex: 1;
  min-width: 200px;
}

.stat-info {
  text-align: center;
  padding: 15px 0;
}

.stat-label {
  color: #606266;
  font-size: 14px;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-desc {
  color: #606266;
  font-size: 14px;
}

.charts-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.chart-card {
  flex: 1;
  min-width: 400px;
  margin-bottom: 20px;
}

.chart-container {
  padding: 15px;
}

.chart {
  width: 100%;
  height: 400px;
  margin-top: 15px;
}
</style>